<template>
  <div>
    <application-header
      title="渠道分析"
      :showChannel="showChannel"
      @getTime="handleGetTime"
      @getChannel="handleGetChannel"
      @getVersion="handleGetVersion"
    />
    <div class="channelAnalysis-container">
      <div class="channelAnalysis-title">
        <span>渠道趋势对比</span>
      </div>
      <div class="channelAnalysis-tabs">
        <a-tabs v-model="tabsKey" @change="callback">
          <a-tab-pane key="1" tab="新增用户">
            <!-- 防止缓存 -->
            <!-- <div class="chart-wrapper" v-if="tabsKey=='1'"> -->
            <div class="chart-wrapper">
              <multipleLine-chart
                legendName="渠道"
                name="新增用户数"
                xAxisName="时间"
                :height="hourHeight"
                :chartData="chartData"
              />
            </div>
          </a-tab-pane>
          <a-tab-pane key="2" tab="活跃用户">
            <div class="chart-wrapper">
              <multipleLine-chart
                legendName="渠道"
                name="活跃用户数"
                xAxisName="时间"
                :height="hourHeight"
                :chartData="chartData"
              />
            </div>
          </a-tab-pane>
          <a-tab-pane key="3" tab="启动次数">
            <div class="chart-wrapper">
              <multipleLine-chart
                legendName="渠道"
                name="启动次数"
                xAxisName="时间"
                :height="hourHeight"
                :chartData="chartData"
              />
            </div>
          </a-tab-pane>
        </a-tabs>
      </div>
      <el-link
        v-if="false"
        style="margin-left: 16px"
        @click="changePutAwayStatus"
        type="primary"
        :underline="false"
        >{{ putAwayName }}明细数据<i
          :class="[
            isPutAway ? 'el-icon-arrow-up' : 'el-icon-arrow-down',
            'el-icon--right',
          ]"
        ></i
      ></el-link>
    </div>
    <div class="channelAnalysis-container">
      <div class="channelAnalysis-title">
        <span>渠道明细数据</span>
      </div>
      <div class="channelAnalysis-radio">
        <a-radio-group v-model="valueDay" @change="onChangeDay">
          <a-radio-button value="a"> 今日 </a-radio-button>
          <a-radio-button value="b"> 昨日 </a-radio-button>
        </a-radio-group>
      </div>
      <div class="channelAnalysis-tables">
        <a-table
          rowKey="id"
          v-if="isPutAway"
          :pagination="pagination"
          :columns="columns"
          :data-source="tableData"
          @change="onChangePagination"
        ></a-table>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import ApplicationHeader from "@/components/ApplicationHeader";
import MultipleLineChart from "@/echartsComponent/MultipleLineChart.vue";
import {
  getYearMonthDayFromOne,
  getYearMonthDay,
  getLastDay,
  getFromDay1ToDay2,
} from "@/utils/functions";
import {
  getSelectChannelNewUserByDate,
  getSelectChannelActiveUserByDate,
  getSelectChannelOpenCountByDate,
} from "@/api/channelAnalysis";

function onChangePagination(pagination, filters, sorter) {
  console.log("params", pagination, filters, sorter);
}

export default {
  name: "ChannelAnalysis",
  data() {
    return {
      valueDay: "a",
      showChannel: false,
      tabsKey: "1",
      hourHeight: "350px",
      chartData: {
        xAxisData: [],
        yAxisData: [],
        legendData: [], // 折线图legend数组
      },
      today: "",
      lastDay: "",
      pagination: {
        pageSize: 10,
        total: 0,
      },
      isPutAway: true,
      data: [],
      lastDayData: [],
      selectData: {
        appKey: "",
        startDate: null,
        endDate: null,
        channel: null,
        version: null,
      },
    };
  },
  components: {
    ApplicationHeader,
    MultipleLineChart,
  },
  computed: {
    putAwayName() {
      return this.isPutAway ? "收起" : "展开";
    },
    ...mapGetters(["applicationId"]),
    columns() {
      if (this.tabsKey == "1") {
        return [
          {
            title: "渠道",
            dataIndex: "channel",
          },
          {
            title: "新增用户",
            dataIndex: "count",
          },
        ];
      } else if (this.tabsKey == "2") {
        return [
          {
            title: "渠道",
            dataIndex: "channel",
          },
          {
            title: "活跃用户",
            dataIndex: "count",
          },
        ];
      } else if (this.tabsKey == "3") {
        return [
          {
            title: "渠道",
            dataIndex: "channel",
          },
          {
            title: "启动次数",
            dataIndex: "count",
          },
        ];
      }
    },
    tableData() {
      if (this.valueDay == "a") {
        this.pagination.total = this.data.length;
        return this.data;
      } else {
        this.pagination.total = this.lastDayData.length;
        return this.lastDayData;
      }
    },
  },
  methods: {
    onChangeDay(e) {
      console.log(`checked = ${e.target.value}`);
    },
    async handleGetTime(msg) {
      this.selectData.startDate = msg[0];
      this.selectData.endDate = msg[1];
      await this.getSelectChannelByDateData(this.selectData, this.tabsKey);
    },
    async handleGetChannel(msg) {
      this.selectData.channel = msg.key;
      await this.getSelectChannelByDateData(this.selectData, this.tabsKey);
    },
    async handleGetVersion(msg) {
      this.selectData.version = msg.key;
      await this.getSelectChannelByDateData(this.selectData, this.tabsKey);
    },
    onChangePagination,
    changePutAwayStatus() {
      this.isPutAway = !this.isPutAway;
    },
    async callback(key) {
      await this.getSelectChannelByDateData(this.selectData, key);
    },
    async getSelectChannelByDateData(data, key) {
      let actionFunc = {
        1: getSelectChannelNewUserByDate,
        2: getSelectChannelActiveUserByDate,
        3: getSelectChannelOpenCountByDate,
      };
      // 每次请求，清空数据
      this.chartData.legendData.length = 0;
      this.chartData.xAxisData.length = 0;
      this.chartData.yAxisData.length = 0;
      this.data.length = 0;
      this.lastDayData.length = 0;
      let res;
      try {
        res = await actionFunc[key](data);
      } catch (error) {
        console.log(error);
      }
      let { code } = res;
      if (code == 0) {
        // 做些什么
        if (res.data.length == 0) {
          this.chartData.xAxisData = [];
          this.chartData.yAxisData = [];
          this.chartData.legendData.length = 0;
          this.data = [];
          this.pagination.total = 0;
        } else {
          this.chartData.xAxisData = getFromDay1ToDay2(
            this.selectData.startDate,
            this.selectData.endDate
          );
          for (let i = 0; i < res.data.length; i++) {
            // 处理table表格
            for (let ti = 0; ti < res.data[i]["data"].length; ti++) {
              // console.log(res.data[i]["data"][ti]["date"], this.today);
              if (res.data[i]["data"][ti]["date"] == this.today) {
                this.data.push({
                  id: "day" + ti,
                  channel: res.data[i]["channel"],
                  count: res.data[i]["data"][ti]["count"],
                });
              }
              if (res.data[i]["data"][ti]["date"] == this.lastDay) {
                this.lastDayData.push({
                  id: "lastDay" + ti,
                  channel: res.data[i]["channel"],
                  count: res.data[i]["data"][ti]["count"],
                });
              }
            }
            // 处理charts数据
            this.chartData.legendData.push(res.data[i].channel);
            // console.log(res.data[i].data);
            let expectArr = [];
            for (let j = 0; j < this.chartData.xAxisData.length; j++) {
              let flag = false;
              let index1;
              // console.log(this.chartData.xAxisData[j]);
              for (let k = 0; k < res.data[i].data.length; k++) {
                // console.log(res.data[i].data[k])
                if (
                  this.chartData.xAxisData[j] == res.data[i].data[k]["date"]
                ) {
                  flag = true;
                  index1 = k;
                  break;
                }
              }
              if (!flag) {
                // 没有找到相同的 往里Push 0
                expectArr[j] = 0;
              } else {
                expectArr[j] = res.data[i].data[index1]["count"];
              }
            }
            // y轴数据结构 [[], [], []]
            this.chartData.yAxisData[i] = expectArr;
          }
          console.log(this.chartData);
        }
      }
    },
  },
  async mounted() {
    this.today = getYearMonthDay();
    this.lastDay = getLastDay();
    this.selectData.appKey = this.applicationId;
    this.selectData.startDate = getYearMonthDayFromOne();
    this.selectData.endDate = getYearMonthDay();
    await this.getSelectChannelByDateData(this.selectData, this.tabsKey);
  },
};
</script>

<style lang="scss" scoped>
.channelAnalysis-container {
  margin: 24px 22px 20px;
  padding: 24px;
  background: #fff;
  border-radius: 5px;
  overflow: hidden;
  .channelAnalysis-title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 32px;
    color: #000;
  }
  .channelAnalysis-tabs {
    position: relative;
    >>> .ant-tabs {
      .ant-tabs-bar {
        border-bottom: none;
        .ant-tabs-nav-container {
          .ant-tabs-nav-wrap {
            .ant-tabs-tab {
              padding: 12px 0;
            }
            .ant-tabs-ink-bar {
              width: 56px;
            }
          }
        }
      }
    }
    // chart
    .chart-wrapper {
      background: #fff;
      padding: 16px 0 0;
      margin-bottom: 32px;
    }
  }
  .channelAnalysis-radio {
    margin: 24px 0px 19px 0px;
    >>> .ant-radio-group {
      .ant-radio-button-wrapper:first-child {
        margin-right: 8px;
      }
    }
  }
  .channelAnalysis-tables {
    margin: 24px auto 16px;
  }
}
</style>